package com.mycase.im.boot.exception;

import com.mycase.im.boot.entity.communication.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

import static com.mycase.im.boot.entity.communication.ResponseMessage.error;
import static com.mycase.im.boot.entity.communication.ResponseMessage.success;

/**
 * @Author ZhuHJay
 * @Date 2021/8/2 17:26
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseMessage exceptionHandler(Exception e){
        String message;

        // 解决 @Validated 注解下的 错误
        if( e instanceof ConstraintViolationException ){
            ConstraintViolationException bindException = (ConstraintViolationException) e;
            message = bindException.getConstraintViolations().iterator().next().getMessage();
            return error(message);
        }
        // 解决 自定义异常 的错误
        else if( e instanceof CustomException ){
            CustomException bindException = (CustomException) e;
            message = bindException.getMessage();
            return error(message);
        }
        // 解决 @Valid JavaBean 参数校验的异常
        else if( e instanceof BindingResult){
            BindingResult bindException = (BindingResult) e;
            message = bindException.getAllErrors().get(0).getDefaultMessage();
            return error(message);
        }

        log.error("错误来源: {}", e);

        return error("系统出现错误");
    }

}
